<template>
  <div v-if="data._isInit">
    <el-collapse-item :title="$t('基础配置')" name="1">
      <el-form-item :label="$t('标题')">
        <el-input v-model="config.title"> </el-input>
      </el-form-item>
    </el-collapse-item>
    <el-collapse-item :title="$t('数据配置')" name="2">
      <el-form-item :label="$t('表单选择')">
        <l-custmerform-select v-model="config.form" @change="custmerformChange" />
      </el-form-item>
      <el-form-item :label="$t('表单版本')">
        <l-select v-model="config.formVerison" :options="formVerisons" />
      </el-form-item>
      <el-form-item :label="$t('排序字段')">
        <l-select v-model="config.orderId" :options="formComponents" placeholder="请选择">
        </l-select>
      </el-form-item>
      <el-form-item :label="$t('行数限制')">
        <el-switch v-model="config.limitRow"> </el-switch>
      </el-form-item>
      <el-form-item v-if="config.limitRow == 1" :label="$t('最大行数')">
        <el-input-number v-model="config.maxRows" controls-position="right" :placeholder="$t('请输入')"></el-input-number>
      </el-form-item>
      <div class="learun-row-form-input" :key="index" v-for="(item, index) in config.columns">
        <el-form-item :label="$t('绑定字段')" style="margin-bottom: 8px">
          <l-select v-model="item.prop" :options="formComponents" @change="handleChangeSelect($event, item)"></l-select>
        </el-form-item>
        <el-form-item :label="$t('宽度')" style="margin-bottom: 8px">
          <el-input v-model="item.width" :placeholder="$t('请输入')">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('对齐')" style="margin-bottom: 0">
          <l-select v-model="item.align" :options="alignOptions"></l-select>
        </el-form-item>

        <el-button :title="$t('删除')" @click="handleRemoveCol(index)" class="learun-row-form-input-delete" circle plain
          size="mini" type="danger">
          <i class="el-icon-close"></i>
        </el-button>
      </div>
      <div style="margin-bottom: 10px">
        <el-button type="primary" size="mini" @click="handleAddCol">{{ $t('添加列') }}</el-button>
      </div>
    </el-collapse-item>
    <el-collapse-item :title="$t('交互设置')" name="3">
      <el-form-item :label="$t('跳转功能')">
        <l-tree-select :options="modulesTree" v-model="config.moduleId">
        </l-tree-select>
      </el-form-item>
      <div style="margin-bottom: 10px">
        <el-button class="ml-8" type="primary" size="mini" @click="handleSettingCondition">{{ $t('设置跳转条件') }}</el-button>
      </div>
    </el-collapse-item>

    <l-dialog title="设置跳转条件" :visible.sync="formVisible" :height="528" :width="720" @ok="handleSave"
      @close="handleCloseForm" @opened="handleOpenedForm">
      <my-form ref="form"></my-form>
    </l-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import configMixins from "../mixins/config";
const apiForm = window.$api.custmerForm.scheme;
import MyForm from "../conditionForm.vue";
export default {
  mixins: [configMixins()],
  inject: ["quickBiDesign"],
  components: {
    MyForm,
  },
  data() {
    return {
      alignOptions: [
        { value: "left", label: "靠左" },
        { value: "center", label: "居中" },
        { value: "right", label: "靠右" },
      ],
      formVisible: false,
    };
  },
  computed: {
    ...mapGetters(["modules"]),
    myModules() {
      return this.modules.filter((t) => t.f_EnabledMark == 1);
    },
    modulesTree() {
      const res = this.$toTree(
        this.myModules,
        "f_ModuleId",
        "f_ParentId",
        "f_ModuleId",
        "f_FullName"
      );
      return res.filter((t) => t.f_ParentId == "0");
    },
  },
  asyncComputed: {
    formVerisons: {
      async get() {
        const { form } = this.config;
        let res = [];
        if (!this.$validatenull(form)) {
          res = await this.$awaitWraper(apiForm.getHistoryList(form));
        }
        return (res || []).map((t) => {
          return { label: this.lr_dateFormat(t.f_CreateDate), value: t.f_Id };
        });
      },
    },
    formComponents: {
      async get() {
        const { formVerison } = this.config;
        if (this.$validatenull(formVerison)) {
          return [];
        }

        if (
          this.$validatenull(this.quickBiDesign.custmerformSchemes[formVerison])
        ) {
          const { f_Scheme, f_Id } =
            (await this.$awaitWraper(
              apiForm.getHistory(this.config.formVerison)
            )) || {};
          this.quickBiDesign.custmerformSchemes[f_Id] = { f_Scheme };
          if (this.config.formVerison == f_Id) {
            return this.loadFormScheme(f_Scheme);
          }
        } else {
          return this.loadFormScheme(
            this.quickBiDesign.custmerformSchemes[formVerison].f_Scheme
          );
        }
        return [];
      },
    },
  },
  methods: {
    init(data) {
      const config = {
        form: "",
        formVerison: "",
        orderId: "",
        limitRow: false,
        maxRows: 10,
        columns: [],
      };
      this.commonInit(data, config);
    },

    custmerformChange(val) {
      if (val == null) {
        this.config.formVerison = "";
      } else {
        this.config.formVerison = val.f_SchemeId;
      }
    },
    handleAddCol() {
      this.config.columns.push({
        prop: "",
        width: 25,
        align: "left",
      });
      console.log(this.config.columns)
    },
    handleRemoveCol(index) {
      this.config.columns.splice(index, 1);
    },
    loadFormScheme(strScheme) {
      const scheme = JSON.parse(strScheme);
      const fields = [];
      scheme.formInfo.tabList.forEach((tab) => {
        tab.components.forEach((component) => {
          if (
            !["gridtable", "divider", "btn", "card"].includes(component.type) &&
            component.display &&
            component.field
          ) {
            //console.log(component.field,'component.field')
            const col = {
              value: `${component.field.toLowerCase()}${scheme.formType == 1
                  ? ""
                  : scheme.db.findIndex((t) => t.name == component.table)
                }`,
              label: component.label,
            };

            const dataTypeRes = this.getComponentDataType(component);
            col.dataType = dataTypeRes.dataType;
            col.dataCode = dataTypeRes.code;
            col.valueKey = dataTypeRes.valueKey;
            col.labelKey = dataTypeRes.labelKey;
            col.options = dataTypeRes.options;
            col.format = dataTypeRes.format;
            if (["rate", "switch"].includes(component.type)) {
              col.setting = component;
            }
            fields.push(col);
          }
        });
      });
      return fields;
    },

    handleSettingCondition() {
      if (this.config.moduleId) {
        const module = this.modules.find(
          (t) => t.f_ModuleId == this.config.moduleId
        );
        if (module.f_Target == "custmerForm") {
          this.formVisible = true;
        } else {
          this.$message({
            type: "warning",
            message: this.$t("目前只支持自定义表单功能设置条件!"),
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: this.$t("请设置跳转功能!"),
        });
      }
    },
    async handleSave() {
      if (this.$refs.form.validateForm()) {
        this.config.conditionInfo = this.$refs.form.getForm();
        this.formVisible = false;
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    handleOpenedForm() {
      this.$refs.form.setForm(this.config.moduleId, this.config.conditionInfo);
    },

    handleChangeSelect(event, item) {
      //console.log(event,item,'event,item')
      if (!event) return;
      item.dataType = event.dataType;
      item.dataCode = event.dataCode;
      item.valueKey = event.valueKey;
      item.labelKey = event.labelKey;
      item.options = event.options;
      item.format = event.format;
      item.setting = event.setting;
    },

    // 表格
    // 获取组件数据类型
    getComponentDataType(compt) {
      const res = {};
      if (
        [
          "radio",
          "checkbox",
          "select",
          "selectMultiple",
          "treeselect",
          "layerselect",
        ].includes(compt.type)
      ) {
        switch (compt.dataType) {
          case "1":
            res.dataType = "mydata";
            res.options = compt.options;
            break;
          case "2":
            res.dataType = "dataItem";
            res.code = compt.dataCode;
            break;
          case "3":
            res.dataType = "dataSource";
            res.code = compt.dataCode;
            res.valueKey = compt.dataValueKey;
            res.labelKey = compt.dataLabelKey;
            break;
        }
      } else if (
        ["datetime", "createtime", "modifytime"].includes(compt.type)
      ) {
        res.dataType = "datetime";
        res.format = compt.format || "yyyy-MM-dd HH:mm:ss";
      } else if (["upload"].includes(compt.type)) {
        res.dataType = "file";
      } else if (["uploadimg"].includes(compt.type)) {
        res.dataType = "img";
      } else if (["companySelect", "company"].includes(compt.type)) {
        res.dataType = "company";
      } else if (["departmentSelect", "department"].includes(compt.type)) {
        res.dataType = "department";
      } else if (
        ["userSelect", "createuser", "modifyuser"].includes(compt.type)
      ) {
        res.dataType = "user";
      } else if (["areaselect"].includes(compt.type)) {
        res.dataType = "areas";
      } else {
        res.dataType = compt.type;
      }
      return res;
    },
  },
};
</script>

